const WS_MODE = {
	MESSAGE: 'MESSAGE',
	HEART_BEAT: 'HEART_BEAT'
}

class Ws extends WebSocket {
	constructor(url,wsReConnect) {
		super(url);
		this.connectedStatus = false
		this.wsUrl = url;
		this.heartBeatTimer = null
		this.reconnectingTimer = null
		this.wsReConnect = wsReConnect
		this.init()
	}

	//开关
	init() {
		this.bindEvent()
	}

	bindEvent() {
		//this就是Ws实例对象
		this.addEventListener('open', this.handleOpen, false)
		this.addEventListener('close', this.handleClose, false)
		this.addEventListener('error', this.handleError, false)
		this.addEventListener('message', this.handleMessage, false)
	}

	handleOpen() {
		// console.log(this, 'this为Ws实例对象')
		console.log('--- Client is connected 客户端已连接  ---')
		this.connectedStatus = true
		this.startHeartBeat()
		//连接开启完毕之后需要开启心跳机制，websocket建立连接之后一段时间不进行操作服务器就会自动断开连接，
		//心跳机制就是为了去检测是否已经断开如果断开了就重连
	}
	handleClose() {
		console.log('--- Client is closed 客户端已关闭 ---')
		this.connectedStatus = false

		if (this.heartBeatTimer) {
			clearInterval(this.heartBeatTimer)
			this.heartBeatTimer = null
		}

		if (this.reconnectingTimer) {
			clearTimeout(this.reconnectingTimer)
			this.reconnectingTimer = null
		}
		//判断客户端已经关闭，关闭了就重连
		this.reconnect()

	}
	handleError(e) {
		console.log('--- Client occured error 客户端出错 ---', e)
		this.connectedStatus = false
		//客户端出错也需要重连
		this.reconnect()
	}
	handleMessage(data) {
		const {
			mode,
			msg
		} = this.receiveMsg(data)
		switch (mode) {
			case WS_MODE.HEART_BEAT:
				this.connectedStatus = true
				console.log('--- HEART_BEAT ---', msg)
				break;
			case WS_MODE.MESSAGE:
				console.log('--- MESSAGE ---', msg)
				break;
			default:
				break;
		}
	}

	//每四秒向服务器发送数据，心跳机制
	startHeartBeat() {
		this.heartBeatTimer = setInterval(() => {
			if (this.readyState === 1) {
				this.sendMsg({
					mode: WS_MODE.HEART_BEAT,
					msg: 'HEART_BEAT'
				})
			} else {
				console.log('执行了')
				clearInterval(this.heartBeatTimer)
				this.heartBeatTimer = null
			}
			this.waitForResponse()
		}, 4000)
	}

	//每三秒向服务器发送urlport，延迟重连
	reconnect() {
		//第一种方式拿不到wsUrl数据因为是异步的
		// reconnectingTimer = setTimeout(()=>{
		// 	Ws.create(this.wsUrl)
		// },3000)
		return new Promise(resolve => {
			this.reconnectingTimer = setTimeout(() => {
				resolve(Ws.create(this.wsUrl))
			}, 3000)
		})
			// this.reconnectingTimer = setTimeout(() => {
			// 	this.wsReConnect()
			// }, 3000)
	}

	//此函数判断转台
	waitForResponse() {
		this.connectedStatus = false
		setTimeout(() => {
			// //如果connectedStatus为true的话，就让他继续心跳机制
			// if (this.connectedStatus) {
			// 	return this.startHeartBeat()
			// }

			// try {
			this.close()
			// } catch (e) {
			// 	console.log('--- Client is closed 捕获 ---')
			// }
		}, 2000)
	}

	//此函数处理接收到的data参数为JSON对象形式
	receiveMsg({
		data
	}) {
		return JSON.parse(data)
	}

	sendMsg(data) {
		this.readyState === 1 && this.send(JSON.stringify(data))
	}

	static create(url,wsReConnect) {
		return new Ws(url,wsReConnect)
	}
}

export default Ws